package day05;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import util.JdbcUtil;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("*.user")
public class UserServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path = request.getServletPath();

        if ("/regist.user".equals(path)) {
            regist(request,response);
        }

        if ("/login.user".equals(path)) {
            login(request,response);
        }

        if ("/logout.user".equals(path)) {
            logout(request,response);
        }
    }

    protected void regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("UserServlet.regist()");

        String username=request.getParameter("username");
        String password=request.getParameter("password");
        String phone=request.getParameter("phone");
        String address=request.getParameter("address");

        Connection con=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        try{
            con= JdbcUtil.getConnection();
            con.setAutoCommit(false);


            String sql=new StringBuffer()
                    .append("select * ")
                    .append("from t_user ")
                    .append("where username=? ")
                    .toString();

            ps=con.prepareStatement(sql);

            ps.setString(1,username);

            rs=ps.executeQuery();

            if(rs.next()){
                con.commit();
                request.setAttribute("message","用户名已存在");
                request.getRequestDispatcher("/shop/regist.jsp").forward(request,response);
                return;
            }

            ps.close();

            sql=new StringBuffer()
                    .append("insert into t_user ")
                    .append("    (username,password,phone,address) ")
                    .append("values ")
                    .append("    (?,?,?,?) ")
                    .toString();

            ps=con.prepareStatement(sql);

            ps.setString(1,username);
            ps.setString(2,password);
            ps.setString(3,phone);
            ps.setString(4,address);

            ps.executeUpdate();



            con.commit();
        }catch (Exception e){
            e.printStackTrace();
            try {
                con.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }finally{
            JdbcUtil.close(rs,ps,con);
        }

        response.sendRedirect(request.getContextPath()+"/shop/login.jsp");

    }

    protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("UserServlet.login()");

        String username=request.getParameter("username");
        String password=request.getParameter("password");

        Connection con=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        try{
            con= JdbcUtil.getConnection();
            con.setAutoCommit(false);


            String sql=new StringBuffer()
                    .append("select * ")
                    .append("from t_user ")
                    .append("where username=? ")
                    .append("and password=? ")
                    .toString();

            ps=con.prepareStatement(sql);

            ps.setString(1,username);
            ps.setString(2,password);

            rs=ps.executeQuery();

            if(rs.next()){
                User user=new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));

                HttpSession session=request.getSession();

                session.setAttribute("user",user);
                session.setAttribute("cart",new Cart());

                response.sendRedirect(request.getContextPath()+"/list.product");

                return;
            }

            request.setAttribute("message","用户名或密码错误");
            request.getRequestDispatcher("/shop/login.jsp").forward(request,response);

            con.commit();
        }catch (Exception e){
            e.printStackTrace();
            try {
                con.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }finally{
            JdbcUtil.close(rs,ps,con);
        }
    }

    protected void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("UserServlet.logout()");

        request.getSession().invalidate();

        response.sendRedirect(request.getContextPath()+"/list.product");
    }


}
